package com.creditcmsplt.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public class Base64Util {

	private static Logger log = LoggerFactory.getLogger(Base64Util.class);

	/**
	 * 文件加密成base64字符
	 * 
	 * @param inputStream
	 *            需要加密的文件输入流
	 * @return 加密后的字符串
	 */
	public static String fileToBase64String(InputStream inputStream) {
		byte[] data = null;
		try {
			data = new byte[inputStream.available()];
			inputStream.read(data);
			inputStream.close();
		} catch (Exception e) {
			log.info("", e);
		}
		return new String(Base64.encodeBase64(data));
	}

	/**
	 * 文件加密成base64字符（单文件）
	 * 
	 * @param file：要加密文件对象
	 * @return 加密后的字符串
	 */
	public static String fileToBase64String(File file) {
		byte[] data = null;
		try {
			InputStream inputStream = new FileInputStream(file);
			data = new byte[inputStream.available()];
			inputStream.read(data);
			inputStream.close();
		} catch (Exception e) {
			log.info("", e);
		}
		return new String(Base64.encodeBase64(data));
	}

	/**
	 * 文件加密成base64字符
	 * 
	 * @param filePath：需要加密的文件路径，全路径
	 * @return 加密后的字符串
	 */
	public static String fileToBase64String(String filePath) {
		byte[] data = null;
		try {
			InputStream inputStream = new FileInputStream(filePath);
			data = new byte[inputStream.available()];
			inputStream.read(data);
			inputStream.close();
		} catch (Exception e) {
			log.info("", e);
		}
		return new String(Base64.encodeBase64(data));
	}

	/**
	 * base64字符解密成文件
	 * 
	 * @param base64Str：需要解密的字符串
	 * @param imagFilePath:需要将文件持久化的位置
	 */
	public static void bs64stringToFile(String base64Str, String imagFilePath) {
		try {
			byte[] bytes = Base64.decodeBase64(base64Str);
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			File imagFileFile = new File(imagFilePath);
			if (!imagFileFile.getParentFile().exists()) {
				imagFileFile.getParentFile().mkdirs();
			}
			OutputStream out = new FileOutputStream(imagFilePath);
			out.write(bytes);
			out.flush();
			out.close();
		} catch (Exception e) {
			log.info("", e);
		}
	}

	public static String bytesConvertBase64Str(byte[] bytes) {
		byte[] bytesTe = Base64.encodeBase64(bytes);
		for (int i = 0; i < bytesTe.length; ++i) {
			if (bytesTe[i] < 0) {// 调整异常数据
				bytesTe[i] += 256;
			}
		}
		return new String(bytesTe);
	}

	/**
	 * base64字符转换成byte数组，以便转换成文件对象
	 * 
	 * @param base64Str
	 * @return byte[]:文件的二进制数据
	 */
	public static byte[] bs64stringToBytes(String base64Str) {
		try {
			byte[] bytes = Base64.decodeBase64(base64Str);
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			return bytes;
		} catch (Exception e) {
			log.info("", e);
		}
		return null;
	}

	public static String StringToBase64(String sourceStr) {
		try {
			byte[] bytes = Base64.encodeBase64(sourceStr.getBytes("UTF-8"));
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			return new String(bytes);
		} catch (UnsupportedEncodingException e) {
			log.info("", e);
		}
		return null;
	}

	public static String base64ToString(String base64Str) {
		try {
			byte[] bytes = Base64.decodeBase64(base64Str.getBytes("UTF-8"));
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			return new String(bytes);
		} catch (UnsupportedEncodingException e) {
			log.info("", e);
		}
		return null;
	}

	/**
	 * 如果base64为图片字符,返回图片格式如：gif、jpeg、png、bmp
	 * 如果不是返回null
	 * @param base64Str
	 */
	public static String getBase64ImgSuffix(String base64Str) {
		String suffix=null;
		try {
			byte[] bytes = Base64.decodeBase64(base64Str.getBytes("UTF-8"));
			ImageInputStream imageInputstream = new MemoryCacheImageInputStream(new ByteArrayInputStream(bytes));
			ImageIO.setUseCache(false);
			Iterator<ImageReader> it = ImageIO.getImageReaders(imageInputstream);
			if (it.hasNext()) {
				ImageReader imageReader = it.next();
				// 设置解码器的输入流
				imageReader.setInput(imageInputstream, true, true);
				suffix = imageReader.getFormatName().trim().toLowerCase();
			}
			imageInputstream.close();
		} catch (Exception e) {
			log.info("", e);
		}
		return suffix;
	}
	
	/**
	 * 判断base64图片编码字符是否为符合要求的图片文件格式,参考jpeg，gif，pang，bmp
	 * @param base64Str:图片base64编码
	 * @param destSuffix：判断目标图片格式
	 * @return 正确返回true，不正确返回false
	 */
	public static boolean checkImage(String base64Str,String destSuffix) {
		String sourceSuffix=getBase64ImgSuffix(base64Str);
		return !TextUtils.isEmpty(sourceSuffix)&&!TextUtils.isEmpty(destSuffix)&&destSuffix.equals(sourceSuffix)?true:false;
	}
	
	/**
	 * 校验文件大小
	 *
	 * @param
	 * @return
	 */
	public static boolean checkSize(byte[] bytes,double imgSize) {
	    //符合条件的照片大小（可配置） 单位：M
	    //double imgSize = 2.0;
	    //图片转base64字符串一般会大，这个变量就是设置偏移量。可配置在文件中，随时修改。目前配的是0。后续看情况适当做修改
	    double deviation = 0.0;
	    int length = bytes.length;
	    //原照片大小
	    double size = (double) length / 1024 / 1024 * (1 - deviation);
	    return size <= imgSize;
	}
	
	/**
	 * 校验文件大小
	 *
	 * @param
	 * @return
	 */
	public static boolean checkSize(String base64Str,double imgSize) {
		try {
			byte[] bytes = Base64.decodeBase64(base64Str.getBytes("UTF-8"));
			return checkSize(bytes, imgSize);
		} catch (Exception e) {
			log.info("", e);
		}
		return false;
	}
	
	public static void main(String[] args) {
	}
}
